<?php

declare(strict_types=1);

namespace App\Controller\playlet;
use App\Controller\BaseController;
use App\Model\DataOrder;
use App\Model\Playlet;
use App\Model\DataOrderPlaylet;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Di\Annotation\Inject;
use App\Common\Response\SystemCode;
use App\Service\playlet\DataOrderService;

#[AutoController]
class DataOrderController  extends BaseController
{

    #[Inject]
    private DataOrderService $dataOrderService;

    /**
     * 订单列表
     */
    public function Index(RequestInterface $request)
    {

        $data = $this->dataOrderService->search($request->query());

        return $this->response(SystemCode::SYSTEM_SUCCESS, '请求成功',$data);


    }
    /**
     * 订单删除
     */
    public function Delete(int $id,RequestInterface $request)
    {
        if(!empty($id)) {
            $DataOrderInfo = DataOrder::query()->where('id', $id)->first();
            if (empty($DataOrderInfo)) {
                return $this->response(SystemCode::SYSTEM_ERROR, '订单不存在');
            }
            $DataOrderInfo->deleted_at = date('Y-m-d H:i:s');
            $DataOrderInfo->save();
            return $this->response(SystemCode::SYSTEM_SUCCESS, '操作成功');
        }
    }
    /**
     * 订单更新
     */
    public function Update(int $id,RequestInterface $request){

        if(empty($id)){
            return $this->response(SystemCode::SYSTEM_ERROR, '错误请求');
        }else{

            $dataOrderInfo = DataOrder::query()->select(['id','data_user_id','phone','status'])->with(['dataUser'])->where('id', $id)->first();

            if(empty($dataOrderInfo)){
                return $this->response(SystemCode::SYSTEM_ERROR, '订单不存在');
            }
            if($request->getMethod() == 'GET'){
                $playletIds = DataOrderPlaylet::query()->where('data_order_id',$id)->pluck('playlet_id');
                if(!empty($playletIds)){
                    $playletName = Playlet::query()->whereIn('id',$playletIds)->pluck('name')->toArray();
                    $dataOrderInfo->playlet_name =implode(",",$playletName);
                }else{
                    $dataOrderInfo->playlet_name = '';
                }
                return $this->response(SystemCode::SYSTEM_SUCCESS, '查询成功',$dataOrderInfo);
            }else{
                $result = $this->dataOrderService->createOrUpdate($request->post(),$dataOrderInfo);

                if($result['code'] == SystemCode::SYSTEM_SUCCESS){
                    return $this->response(SystemCode::SYSTEM_SUCCESS, '修改成功');
                }else{
                    return $this->response(SystemCode::SYSTEM_ERROR, $result['message']);

                }
            }
        }
    }

}